/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pa165.dominating.species.security;

import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pa165.dominating.species.dao.UserDAO;
import pa165.dominating.species.entities.User;
import pa165.dominating.species.enums.UserType;
import pa165.dominating.species.exceptions.DataStorageException;

/**
 *
 * @author Filip Dinh
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDAO userDAO;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user;
        try {
            user = userDAO.getUserByUserName(username);
        } catch (DataStorageException e) {
            user = null;
        }
        if (user != null) {
            String password = user.getPassword();

            Collection<GrantedAuthority> authorities = new ArrayList<>();

            authorities.add(new GrantedAuthorityImpl(user.getType().name()));
            if(user.getType() == UserType.ADMIN){
                authorities.add(new GrantedAuthorityImpl(UserType.WORKER.name()));
            }

            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authorities);
            return securityUser;
        } else {
            throw new UsernameNotFoundException("User Not Found!!!");
        }
    }
}
